package com.cdlj.moes.common;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.TextView;

import com.cdlj.moes.dao.UserInfoSQLiteHelper;

public class Utils {
    public static boolean exitFlag = false;
    private static boolean mHaveSignIn = false;

    public static void checkConnection(Context mContext) {
        boolean checkFlag = false;
        ConnectivityManager connectivity = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            checkFlag = false;
        } else {
            NetworkInfo[] infos = connectivity.getAllNetworkInfo();
            if (infos != null) {
                for (int i = 0; i < infos.length; i++) {
                    if (infos[i].getState() == NetworkInfo.State.CONNECTED) {
                        checkFlag = true;
                    }

                }
            }
        }

        if (!checkFlag) {
            exitFlag = true;
        }

    }

    public static boolean isInternetAvailable(Context mContext) {
        boolean checkFlag = false;
        ConnectivityManager connectivity = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            checkFlag = false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        checkFlag = true;

                    }
                }
            }
        }
        return checkFlag;
    }

    public static String replacePlaceholder(String msg, String[] attrs) {
        if (attrs == null) {
            return msg;
        }
        for (int i = 0; i < attrs.length; i++) {
            msg = msg.replace("{" + i + "}", attrs[i]);
        }
        return msg;
    }


    public static void displayInfo(String info, TextView infoView) {
        infoView.setText(info);
        infoView.setVisibility(View.VISIBLE);
    }

    public static void hideInfo(TextView infoView) {
        infoView.setVisibility(View.INVISIBLE);
    }

    public static void textViewGone(TextView infoView) {
        infoView.setVisibility(View.GONE);
    }

    public static void setClearIcon(final EditText mEditText, final Drawable clearDrawable) {
        mEditText.setCompoundDrawables(null, null, clearDrawable, null);
        mEditText.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getX() > mEditText.getMeasuredWidth() - mEditText.getPaddingRight()
                        - clearDrawable.getIntrinsicWidth()) {
                    mEditText.setText("");
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    public static boolean checkUserIsSignIn(Context mContext) {
        Cursor mCursor = UserInfoSQLiteHelper.getInstance(mContext).getUserInfo();
        ((Activity) mContext).startManagingCursor(mCursor);
        if (mCursor == null || mCursor.getCount() == 0) {
            mHaveSignIn = false;
        } else {
            mHaveSignIn = true;
        }
        return mHaveSignIn;
    }

    public static String[] checkGPSCoordinateByName(String carparkName, Context context) {
        Log.i(Constants.APP_TAG, "checkGPSCoordinateByName");
        // Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        String[] gpsCoordinate = new String[2];
      //  String response = Service.checkGPSCoordinateByName(carparkName);
        // try {//TODO:replace method to retrieve using web-based method
        // List<Address> location = geocoder.getFromLocationName(carparkName +
        // ",Singapore", 1);
        // if (location.size() > 0) {
        // Address address = location.get(0);
        // gpsCoordinate[0] = String.valueOf(address.getLatitude());
        // gpsCoordinate[1] = String.valueOf(address.getLongitude());
        // } else {
        // gpsCoordinate[0] = AppConstant.BLANK;
        // gpsCoordinate[1] = AppConstant.BLANK;
        // response = Service.checkGPSCoordinateByName(carparkName);
        // }
        // } catch (IOException e) {
        // gpsCoordinate[0] = AppConstant.BLANK;
        // gpsCoordinate[1] = AppConstant.BLANK;
        // response = Service.checkGPSCoordinateByName(carparkName);
        // e.printStackTrace();
        // }
//        if ("".equals(response)) {
//            gpsCoordinate[0] = AppConstant.BLANK;
//            gpsCoordinate[1] = AppConstant.BLANK;
//        } else {
//            try {
//                JSONObject jsonObject = new JSONObject(response);
//                JSONArray jsonArray = jsonObject.getJSONArray("results");
//                JSONObject jsonObject2 = jsonArray.getJSONObject(0);
//                jsonObject2.names();
//                JSONObject locationJsonObject = jsonObject2.getJSONObject("geometry").getJSONObject("location");
//                gpsCoordinate[0] = locationJsonObject.getString("lat");
//                gpsCoordinate[1] = locationJsonObject.getString("lng");
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
//        Log.i(AppConstant.APP_TAG, "GPS Coordinate for [" + carparkName + ", Singapore] is [" + gpsCoordinate[0] + ", "
//                + gpsCoordinate[1] + "]");
        return gpsCoordinate;
    }

    public static String getLocationName(double latitude, double longitude, Context context, String defaultMsg) {
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        StringBuffer stringBuffer = new StringBuffer();
        try {
            List<Address> address = geocoder.getFromLocation(latitude, longitude, 1);
            if (address.size() > 0) {
                Address addressMsg = address.get(0);
                String address1 = addressMsg.getAddressLine(0);
                String address2 = addressMsg.getAddressLine(1);
                stringBuffer.append(address1);
                stringBuffer.append(",");
                stringBuffer.append(address2);
            } else {
                stringBuffer.append(defaultMsg);
            }
        } catch (Exception e) {
            stringBuffer.append(defaultMsg);
        }
        return stringBuffer.toString().trim();
    }
}
